﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using Castle.Services.Transaction;
using Meqs.Entity;
using Meqs.Entity.Parameters;
using Meqs.Logic.Interface;

namespace Meqs.Logic.Implement
{
    public class ClassEvalSubmitRecordLogic : CommonLogic<ClassEvalSubmitRecord, int>, IClassEvalSubmitRecordLogic
    {
        private ISchoolInfoLogic _schoolLogic;
        private IClassEvalListLogic _celLogic;
        private IClassEvalDetailLogic _cdLogic;
        private IClassEvalRemarkLogic _crLogic;
        private IClassEvalHistoryLogic _chLogic;
        private IClassEvalCatchLogic _cpcLogic;
        private IClassEvalTypeCatchLogic _cptcLogic;
        private IClassEvalItemCatchLogic _cpicLogic;
        private IClassEvalItemLogic _ciLogic;

        public ClassEvalSubmitRecordLogic(ISchoolInfoLogic schoolLogic,
                                        IClassEvalListLogic celLogic,
                                        IClassEvalDetailLogic cdLogic,
                                        IClassEvalRemarkLogic crLogic,
                                        IClassEvalHistoryLogic chLogic,
                                        IClassEvalCatchLogic cpcLogic,
                                        IClassEvalTypeCatchLogic cptcLogic,
                                        IClassEvalItemCatchLogic cpicLogic,
                                        IClassEvalItemLogic ciLogic)
        {
            _schoolLogic = schoolLogic;
            _celLogic = celLogic;
            _cdLogic = cdLogic;
            _crLogic = crLogic;
            _chLogic = chLogic;
            _cpcLogic = cpcLogic;
            _cptcLogic = cptcLogic;
            _cpicLogic = cpicLogic;
            _ciLogic = ciLogic;
        }

        #region Implementation of ICommonLogic<ClassEvalSubmitRecord, int>

        /// <summary>
        /// 创建对象
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        public int Create(ClassEvalSubmitRecord entity)
        {
            return CreateObject(entity);
        }

        /// <summary>
        /// 更新对象
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        public int Update(ClassEvalSubmitRecord entity)
        {
            return UpdateObject(entity);
        }

        /// <summary>
        /// 删除对象
        /// </summary>
        /// <param name="entityId"></param>
        /// <returns></returns>
        public int Delete(int entityId)
        {
            return DeleteObject(entityId);
        }

        /// <summary>
        /// 删除所有对象
        /// </summary>
        /// <returns></returns>
        public int DeleteAll()
        {
            return DeleteAllObject();
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="entityId"></param>
        /// <returns></returns>
        public ClassEvalSubmitRecord FindById(int entityId)
        {
            return FindObjectById(entityId);
        }

        /// <summary>
        /// 检索对象数量
        /// </summary>
        /// <returns></returns>
        public int FindCount()
        {
            return FindObjectByCount();
        }

        /// <summary>
        /// 检索对象
        /// </summary>
        public IList<ClassEvalSubmitRecord> FindAll()
        {
            return FindAllObject();
        }

        /// <summary>
        /// 检索对象数量
        /// </summary>
        /// <returns></returns>
        public int FindCount(Hashtable table)
        {
            return FindObjectByCount(table);
        }

        /// <summary>
        /// 检索对象
        /// </summary>
        public IList<ClassEvalSubmitRecord> FindAll(Hashtable table)
        {
            return FindObject(table);
        }

        #endregion

        /// <summary>
        /// 保存记录
        /// </summary>
        /// <param name="list"></param>
        /// <param name="reportType"></param>
        /// <param name="evalDate"></param>
        /// <param name="schoolYear"></param>
        /// <param name="term"></param>
        /// <param name="teacherID"></param>
        /// <param name="schoolMark"></param>
        /// <returns></returns>
        [Transaction(TransactionMode.Supported)]
        public bool SaveOrUpdateRecord(int historyID, IList<ClassItems> list, int reportType, DateTime evalDate, int? schoolYear, int? term, int teacherID, string schoolMark)
        {
            try
            {
                if (schoolYear == null || term == null)
                {
                    SchoolInfo school = _schoolLogic.FindBySchoolMark(schoolMark);
                    schoolYear = school.SchoolYear;
                    term = school.SchoolTerm;
                }
                ClassEvalList mel = _celLogic.GetEvalList(historyID, reportType, evalDate, schoolYear, term, schoolMark);

                // 如果评价记录为空，则插入一条记录
                if (mel == null)
                {
                    mel = new ClassEvalList();
                    mel.HistoryID = historyID;
                    mel.StartTime = evalDate;
                    mel.Attribute = reportType;

                    int melID = _celLogic.InsertClassEvalList(mel, schoolMark);
                    mel.RID = melID;
                }

                foreach (ClassItems c in list)
                {
                    ClassEvalSubmitRecord csr = GetRecordByCls(mel.RID, c.ClassID, reportType, evalDate, schoolYear, term, schoolMark);
                    //MoralityHistory mh = _mhLogic.GetHistoryRecordByTerm((int)schoolYear, (int)term, schoolMark);

                    // 如果评价提交记录为空，则插入一条记录
                    if (csr == null)
                    {
                        csr = new ClassEvalSubmitRecord();
                        csr.ClassID = c.ClassID;
                        csr.ListID = mel.RID;
                        csr.ManagerID = teacherID;
                        //csr.Status = 1;

                        int msrID = InsertClassEvalSubmitRecord(csr, schoolMark);
                        csr.RID = msrID;
                    }

                    // 清空该班的评价和备注
                    DeleteAllRecord(csr.RID, schoolMark);
                    IList<int> classIDList = new List<int>();

                    if (list == null) return true;
                    Dictionary<int, double> dicMpc = new Dictionary<int, double>();
                    Dictionary<DicKey, double> dicMptc = new Dictionary<DicKey, double>();
                    Dictionary<DicKey, double[]> dicMpic = new Dictionary<DicKey, double[]>();

                    // 保存备注
                    if (!string.IsNullOrEmpty(c.Remark))
                    {
                        ClassEvalRemark mr = new ClassEvalRemark();
                        mr.RecordID = csr.RID;
                        mr.ClassID = c.ClassID;
                        mr.Data = c.Remark;
                        _crLogic.InserClassEvalRemark(mr, schoolMark);
                    }

                    // 保存评价
                    if (c.ClsItems != null && c.ClsItems.Count > 0)
                    {
                        foreach (ClsDetailItems item in c.ClsItems)
                        {
                            ClassEvalDetail md = new ClassEvalDetail();
                            md.Itemid = item.ClassEvalItemID;
                            md.RecordID = csr.RID;
                            md.ClassID = item.ClassID;
                            md.Param = item.Param;

                            _cdLogic.InsertClassEvalDetail(md, schoolMark);
                            if (!classIDList.Contains((int)md.ClassID))
                                classIDList.Add((int)md.ClassID);


                                #region 计算每套题目的总分

                                if (dicMpc.ContainsKey((int)md.ClassID))
                                //if (ContainsKey(dicMpc, (int)md.StudentID))
                                {
                                    double allScore = dicMpc[(int)md.ClassID];
                                    allScore += item.Type == 1 ? item.Param : item.Param * item.Score * item.Operator;
                                    dicMpc[(int)md.ClassID] = allScore;
                                }
                                else
                                {
                                    dicMpc[(int)md.ClassID] = item.Type == 1 ? item.Param : item.Param * item.Score * item.Operator;
                                }

                                #endregion

                                ClassEvalItem mi = _ciLogic.GetItemByID(schoolMark, (int)md.Itemid);
                                #region 计算每道大题的分数

                                DicKey mptcKey = new DicKey((int)md.ClassID, (int)mi.TypeID);
                                if (dicMptc.ContainsKey(mptcKey))
                                //if (ContainsKey(dicMptc, mptcKey))
                                {
                                    double allScore = dicMptc[mptcKey];
                                    allScore += item.Type == 1 ? item.Param : item.Param * item.Score * item.Operator;
                                    dicMptc[mptcKey] = allScore;
                                }
                                else
                                {
                                    dicMptc[mptcKey] = item.Type == 1 ? item.Param : item.Param * item.Score * item.Operator;
                                }

                                #endregion

                                #region 计算每道小题的分数

                                DicKey mpicKey = new DicKey((int)md.ClassID, mi.RID);
                                if (dicMpic.ContainsKey(mpicKey))
                                //if (ContainsKey(dicMpic, mpicKey))
                                {
                                    double allScore = dicMpic[mpicKey][0];
                                    double allParam = dicMpic[mpicKey][1];
                                    allScore += item.Type == 1 ? item.Param : item.Param * item.Score * item.Operator;
                                    allParam += item.Param;
                                    dicMpic[mpicKey] = new double[] { allScore, allParam };
                                }
                                else
                                {
                                    double allScore = item.Type == 1 ? item.Param : item.Param * item.Score * item.Operator;
                                    double allParam = item.Param;
                                    dicMpic[mpicKey] = new double[] { allScore, allParam };
                                }

                                #endregion
                        }
                    }

                    foreach (int classID in classIDList)
                    {
                        // 计算缓存表

                        // 1. 将结果汇总到每张单据中每班的总分(表:ClassEvalPersonCatch)
                        int recordID = csr.RID;
                        // 先删除
                        _cpcLogic.DeleteClassEvalCatch(classID, recordID, schoolMark);
                        // 再插入
                        ClassEvalCatch mpc = new ClassEvalCatch();
                        mpc.RecordID = recordID;
                        mpc.ClassID = classID;
                        double score = dicMpc[classID];
                        mpc.Score = score;
                        mpc.Dirty = 0;
                        _cpcLogic.InsertClassEvalCatch(mpc, schoolMark);

                        // 2. 将结果汇总到每张单据中每道大题每个人的得分(表:ClassEvalTypeCatch)
                        _cptcLogic.DeleteClassEvalTypeCatch(classID, recordID, schoolMark);
                        foreach (KeyValuePair<DicKey, double> dictionary in dicMptc)
                        {
                            if (dictionary.Key.StudentID != classID) continue;
                            ClassEvalTypeCatch mptc = new ClassEvalTypeCatch();
                            mptc.Dirty = 0;
                            mptc.RecordID = recordID;
                            mptc.Score = dictionary.Value;
                            mptc.ClassID = classID;
                            mptc.TypeID = dictionary.Key.ItemID;
                            _cptcLogic.InsertClassEvalTypeCatch(mptc, schoolMark);
                        }

                        // 3. 将结果汇总到每张单据中每道小题每个人的得分(表:MoralityPersonItemCatch)
                        _cpicLogic.DeleteClassEvalItemCatch(classID, recordID, schoolMark);
                        foreach (KeyValuePair<DicKey, double[]> dictionary in dicMpic)
                        {
                            if (dictionary.Key.StudentID != classID) continue;
                            ClassEvalItemCatch mpic = new ClassEvalItemCatch();
                            mpic.Dirty = 0;
                            mpic.ItemID = dictionary.Key.ItemID;
                            mpic.Param = dictionary.Value[1];
                            mpic.RecordID = recordID;
                            mpic.Score = dictionary.Value[0];
                            mpic.ClassID = classID;
                            _cpicLogic.InsertClassEvalItemCatch(mpic, schoolMark);
                        }
                    }
                }
                return true;
            }
            catch (Exception)
            {
                return false;
            }
        }

        /// <summary>
        /// 保存
        /// </summary>
        public int InsertClassEvalSubmitRecord(ClassEvalSubmitRecord classEvalSubmitRecord, string schoolMark)
        {
            Hashtable ht = new Hashtable();
            ht.Add("ClassEvalSubmitRecord", classEvalSubmitRecord);
            ht.Add("SchoolMark", schoolMark);
            return (int)InsertCustomer("ClassEvalSubmitRecord.InsertClassEvalSubmitRecord", ht);
        }

        /// <summary>
        /// 清空记录
        /// </summary>
        public int DeleteAllRecord(int recordID, string schoolMark)
        {
            Hashtable ht = new Hashtable();
            ht.Add("RecordID", recordID);
            ht.Add("SchoolMark", schoolMark);
            return DeleteCustomer("ClassEvalSubmitRecord.DeleteAllRecord", ht);
        }

        /// <summary>
        /// 获取评价提交记录
        /// </summary>
        private ClassEvalSubmitRecord GetRecordByCls(int listID, int clsID, int reportType, DateTime evalDate, int? schoolYear, int? term, string schoolMark)
        {
            try
            {
                Hashtable ht = new Hashtable();
                ht.Add("SchoolMark", schoolMark);
                ht.Add("ClsID", clsID);
                ht.Add("ReportDate", evalDate);
                ht.Add("ReportType", reportType);
                ht.Add("SchoolYear", schoolYear);
                ht.Add("Term", term);
                ht.Add("ListID", listID);
                return FindCustomerByID<ClassEvalSubmitRecord>("ClassEvalSubmitRecord.GetRecordByCls", ht);
            }
            catch (Exception)
            {
                return null;
            }
        }

    }
}
